#include "dir.h"
#include "../utility/utility.h"

namespace losor
{
	dir::dir( string path, string name, object *parent ):
		object( "dir", name, parent ),
		m_path( path )
	{
		// TODO:
	}
		
	dir::~dir()
	{
		// TODO:
	}
	
	long dir::parse( string para, object *parent )
	{
#ifdef _WIN32
		WIN32_FIND_DATA FindFileData;
		HANDLE hFind;
		BOOL ret = TRUE;
		
		char fpath[4096];
		object *child;
		char *name;

		sprintf( fpath, "%s\\*", m_path.c_str() );
		hFind = FindFirstFile( fpath, &FindFileData );
		while( 1 )
		{
			if( !ret && GetLastError() == ERROR_NO_MORE_FILES )
				break;
			name = strutil::lowwer( FindFileData.cFileName );
			if( FindFileData.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY )
			{
				if( strcmp( name, "." ) != 0 && strcmp( name, ".." ) != 0 )
				{
					sprintf( fpath, "%s\\%s", m_path.c_str(), name );
					child = new dir( fpath, name, this );
					child->parse( fpath, this );
					add_child( child );
				}
			}
			else if( strutil::is_src_ext( name ) )
			{
				sprintf( fpath, "%s\\%s", m_path.c_str(), name.c_str() );
				child = new file( fpath, name, this );
				child->parse( fpath, this );
				add_child( child );
			}
			strutil::free( name );
			ret = FindNextFile( hFind, &FindFileData );
		}
		FindClose(hFind);
#endif
	}
	
	long dir::write_depend( object *parent )
	{
		list<object*>::iterator i;
		for( i = m_child.begin(); i != m_child.end(); ++i )
			(*i)->write_depend( this );
		return 0;
	}
	
	string dir::path() const
	{
		return m_path;
	}
	
	void dir::rm_child( string para )
	{
		file *_file;
		list<object*>::iterator i;
		for( i = m_child.begin(); i != m_child.end(); ++i )
		{
			_file = (file*)*i;
			if( _file->fullpath() == para )
			{
				m_child.erase( i );
				break;
			}
		}
	}
	
}

